package com.kerrykidz.system.util.sync;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import javax.jms.DeliveryMode;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

import com.kerrykidz.common.Constants;
import com.kerrykidz.system.util.SystemParaSingleton;

public class FileSyncTask extends QuartzJobBean {

	// 查询上一次执行的时间
	private final static String QUERY_SQL = "SELECT MAX(SYNC_TIME) FROM SYS_FILE_SYNC";

	@Override
	protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
		long previousTime = getPreviousExecuteTime();
		long currentTime = getAndSetCurrentTime();
		List<Long[]> times = cutLongTime(previousTime, currentTime);
		String[] queueNames = ActiveMQHelper.getFileQueueName();
		for (Long[] time : times) {
			HashMap<String, List<FileMessage>> message = collectFile(time);
			if (message.size() > 0)
				for (String queueName : queueNames)
					ActiveMQHelper.push2broker(message, queueName, DeliveryMode.NON_PERSISTENT);
		}
		this.insertDb(currentTime);
	}

	private List<FileMessage> findFiles(String avatarPath, Long[] time) {
		File fil = new File(avatarPath);
		if (fil.exists() && fil.isDirectory()) {
			File[] files = fil.listFiles();
			if (files.length > 0) {
				List<FileMessage> list = new ArrayList<FileMessage>();
				for (File file : files) {
					if (!file.isDirectory()) {
						String fileName = file.getName();
						String preffix = subFileName(fileName);
						Long longTime;
						try {
							longTime = Long.parseLong(preffix);
						} catch (Exception e) {
							longTime = null;
						}
						if (longTime != null && longTime <= time[1] && longTime > time[0]) {
							InputStream is = null;
							try {
								is = new FileInputStream(file);
								byte bys[] = new byte[is.available()];
								is.read(bys);
								list.add(new FileMessage(fileName, bys));
							} catch (FileNotFoundException e) {
								e.printStackTrace();
							} catch (IOException e) {
								e.printStackTrace();
							} finally {
								try {
									if (is != null)
										is.close();
								} catch (IOException e) {
									e.printStackTrace();
								}
							}
						}
					}
				}
				return list;
			}
		}
		return null;
	}

	private String subFileName(String fileName) {
		if (fileName.indexOf(".") > -1)
			return fileName.substring(0, fileName.lastIndexOf("."));
		return null;
	}

	private HashMap<String, List<FileMessage>> collectFile(Long[] time) {
		HashMap<String, List<FileMessage>> fileMap = new HashMap<String, List<FileMessage>>();
		String avatarPath = SystemParaSingleton.getInstance().getValue(Constants.SYS_BASE_PATH_AVATAR);
		String contPath = SystemParaSingleton.getInstance().getValue(Constants.SYS_BASE_PATH_CONT);
		String fetePath = SystemParaSingleton.getInstance().getValue(Constants.SYS_BASE_PATH_FETE);
		String imagePath = SystemParaSingleton.getInstance().getValue(Constants.SYS_BASE_PATH_IMAGE);
		String parhetongPath = SystemParaSingleton.getInstance().getValue(Constants.SYS_BASE_PATH_PARHETONG);
		String signPath = SystemParaSingleton.getInstance().getValue(Constants.SYS_BASE_PATH_SIGN);
		String signformPath = SystemParaSingleton.getInstance().getValue(Constants.SYS_BASE_PATH_SIGNFORM);
		String stockPath = SystemParaSingleton.getInstance().getValue(Constants.SYS_BASE_PATH_STOCK);
		String tsignPath = SystemParaSingleton.getInstance().getValue(Constants.SYS_BASE_PATH_TSIGN);
		String agmPath = SystemParaSingleton.getInstance().getValue(Constants.SYS_PATH_SUP_AGM);

		List<FileMessage> avatarList = findFiles(avatarPath, time);
		List<FileMessage> contList = findFiles(contPath, time);
		List<FileMessage> feteList = findFiles(fetePath, time);
		List<FileMessage> imageList = findFiles(imagePath, time);
		List<FileMessage> parhetongList = findFiles(parhetongPath, time);
		List<FileMessage> signList = findFiles(signPath, time);
		List<FileMessage> signformList = findFiles(signformPath, time);
		List<FileMessage> stockList = findFiles(stockPath, time);
		List<FileMessage> tsignList = findFiles(tsignPath, time);
		List<FileMessage> agmList = findFiles(agmPath, time);

		if (avatarList != null && avatarList.size() > 0)
			fileMap.put(Constants.SYS_BASE_PATH_AVATAR, avatarList);
		if (contList != null && contList.size() > 0)
			fileMap.put(Constants.SYS_BASE_PATH_CONT, contList);
		if (feteList != null && feteList.size() > 0)
			fileMap.put(Constants.SYS_BASE_PATH_FETE, feteList);
		if (imageList != null && imageList.size() > 0)
			fileMap.put(Constants.SYS_BASE_PATH_IMAGE, imageList);
		if (parhetongList != null && parhetongList.size() > 0)
			fileMap.put(Constants.SYS_BASE_PATH_PARHETONG, parhetongList);
		if (signList != null && signList.size() > 0)
			fileMap.put(Constants.SYS_BASE_PATH_SIGN, signList);
		if (signformList != null && signformList.size() > 0)
			fileMap.put(Constants.SYS_BASE_PATH_SIGNFORM, signformList);
		if (stockList != null && stockList.size() > 0)
			fileMap.put(Constants.SYS_BASE_PATH_STOCK, stockList);
		if (tsignList != null && tsignList.size() > 0)
			fileMap.put(Constants.SYS_BASE_PATH_TSIGN, tsignList);
		if (agmList != null && agmList.size() > 0)
			fileMap.put(Constants.SYS_PATH_SUP_AGM, agmList);

		return fileMap;
	}

	private List<Long[]> cutLongTime(long previousTime, long currentTime) {
		return SyncParamHelper.getTaskIntervalDate(currentTime, previousTime, Calendar.MINUTE, 30);
	}

	private long getAndSetCurrentTime() {
		long current = System.currentTimeMillis();
		return current;
	}

	private synchronized long getPreviousExecuteTime() {
		Long pre = this.queryFromDb(); // 从数据库查询上一次执行时间
		if (pre == null) // 如果一次都没执行过
			pre = this.insertDb(SyncParamHelper.TASK_CYCLE_CONSTANTLY_START_DATE.getTime()); // 插入一条记录，从配置文件kerrykidz.properties里获取的第一次执行时间
		return pre;
	}

	private long insertDb(long time) {
		// 为什么不把这个SQL放到常量里去呢? 自己慢慢想!
		String sql = "INSERT INTO SYS_FILE_SYNC (SYNC_TIME) VALUES(?)";
		SqlHelper.executeUpdate(sql, time);
		return time;
	}

	private Long queryFromDb() {
		try {
			return SqlHelper.getJdbcTemplate().queryForObject(QUERY_SQL, Long.class);
		} catch (Exception e) {
			return null;
		}
	}

	public static void main(String[] args) {
		String path = "C:\\kerrykidz\\a\\b\\d";
		File f = new File(path);
		for (File fil : f.listFiles())
			System.out.println(fil.getName());
		System.out.println(Long.parseLong("1414s"));
	}
}
